package com.yjq.programmer.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yjq.programmer.bean.CodeMsg;
import com.yjq.programmer.dao.MusicMenuItemMapper;
import com.yjq.programmer.dao.MusicMenuMapper;
import com.yjq.programmer.dao.UserMapper;
import com.yjq.programmer.domain.*;
import com.yjq.programmer.dto.*;
import com.yjq.programmer.service.IMusicMenuService;
import com.yjq.programmer.service.IUserService;
import com.yjq.programmer.utils.CommonUtil;
import com.yjq.programmer.utils.CopyUtil;
import com.yjq.programmer.utils.UuidUtil;
import com.yjq.programmer.utils.ValidateEntityUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @author 杨杨吖
 * @QQ 823208782
 * @WX yjqi12345678
 * @create 2022-11-21 16:21
 */
@Service
@Transactional
public class MusicMenuServiceImpl implements IMusicMenuService {

    @Resource
    private MusicMenuMapper musicMenuMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private IUserService userService;

    @Resource
    private MusicMenuItemMapper musicMenuItemMapper;

    /**
     * 分页获取歌单数据
     * @param pageDTO
     * @return
     */
    @Override
    public ResponseDTO<PageDTO<MusicMenuDTO>> getMusicMenuListByPage(PageDTO<MusicMenuDTO> pageDTO) {
        MusicMenuExample musicMenuExample = new MusicMenuExample();
        // 判断是否进行关键字搜索
        MusicMenuDTO searchMusicMenuDTO = pageDTO.getSearchEntity();
        MusicMenuExample.Criteria criteria = musicMenuExample.createCriteria();
        if(!CommonUtil.isEmpty(searchMusicMenuDTO.getName())) {
            criteria.andNameLike("%" + searchMusicMenuDTO.getName() + "%");
        }
        // 不知道当前页多少，默认为第一页
        if(pageDTO.getPage() == null){
            pageDTO.setPage(1);
        }
        if(pageDTO.getSize() == null) {
            pageDTO.setSize(5);
        }
        musicMenuExample.setOrderByClause("create_time desc");
        PageHelper.startPage(pageDTO.getPage(), pageDTO.getSize());
        // 分页查出歌单数据
        List<MusicMenu> musicMenuList = musicMenuMapper.selectByExample(musicMenuExample);
        PageInfo<MusicMenu> pageInfo = new PageInfo<>(musicMenuList);
        // 获取数据的总数
        pageDTO.setTotal(pageInfo.getTotal());
        // 将domain类型数据  转成 DTO类型数据
        List<MusicMenuDTO> musicMenuDTOList = CopyUtil.copyList(musicMenuList, MusicMenuDTO.class);
        pageDTO.setList(musicMenuDTOList);
        return ResponseDTO.success(pageDTO);
    }

    /**
     * 保存歌单数据(添加、修改)
     * @param musicMenuDTO
     * @return
     */
    @Override
    public ResponseDTO<Boolean> saveMusicMenu(MusicMenuDTO musicMenuDTO) {
        // 进行统一表单验证
        CodeMsg validate = ValidateEntityUtil.validate(musicMenuDTO);
        if(!validate.getCode().equals(CodeMsg.SUCCESS.getCode())){
            return ResponseDTO.errorByMsg(validate);
        }
        MusicMenu musicMenu = CopyUtil.copy(musicMenuDTO, MusicMenu.class);
        User user = userMapper.selectByPrimaryKey(musicMenu.getUserId());
        if(null == user) {
            return ResponseDTO.errorByMsg(CodeMsg.USER_NOT_EXIST);
        }
        musicMenu.setUsername(user.getUsername());
        musicMenu.setHeadPic(user.getHeadPic());
        if(CommonUtil.isEmpty(musicMenu.getId())){
            // id为空 说明是添加数据
            // 判断该用户的歌单是否存在
            if(isMusicMenuExist(musicMenu, "")){
                return ResponseDTO.errorByMsg(CodeMsg.MUSIC_MENU_NAME_EXIST);
            }
            // 生成8位id
            musicMenu.setId(UuidUtil.getShortUuid());
            musicMenu.setCreateTime(new Date());
            // 添加数据到数据库
            if(musicMenuMapper.insertSelective(musicMenu) == 0){
                return ResponseDTO.errorByMsg(CodeMsg.MUSIC_MENU_ADD_ERROR);
            }
        }else{
            // id不为空 说明是修改数据
            // 判断该用户的歌单是否存在
            if(isMusicMenuExist(musicMenu, musicMenu.getId())){
                return ResponseDTO.errorByMsg(CodeMsg.MUSIC_MENU_NAME_EXIST);
            }
            // 修改数据库中数据
            if(musicMenuMapper.updateByPrimaryKeySelective(musicMenu) == 0){
                return ResponseDTO.errorByMsg(CodeMsg.MUSIC_MENU_EDIT_ERROR);
            }
        }
        return ResponseDTO.successByMsg(true, "保存成功！");
    }

    /**
     * 删除歌单数据
     * @param musicMenuDTO
     * @return
     */
    @Override
    public ResponseDTO<Boolean> removeMusicMenu(MusicMenuDTO musicMenuDTO) {
        if(CommonUtil.isEmpty(musicMenuDTO.getId())){
            return ResponseDTO.errorByMsg(CodeMsg.DATA_ERROR);
        }
        // 删除歌单下所有音乐信息
        MusicMenuItemExample musicMenuItemExample = new MusicMenuItemExample();
        musicMenuItemExample.createCriteria().andMusicIdEqualTo(musicMenuDTO.getId());
        musicMenuItemMapper.deleteByExample(musicMenuItemExample);
        // 删除歌单信息
        if(musicMenuMapper.deleteByPrimaryKey(musicMenuDTO.getId()) == 0){
            return ResponseDTO.errorByMsg(CodeMsg.MUSIC_MENU_DELETE_ERROR);
        }
        return ResponseDTO.successByMsg(true, "删除成功！");
    }

    /**
     * 小程序保存歌单数据(添加、修改)
     * @param musicMenuDTO
     * @return
     */
    @Override
    public ResponseDTO<Boolean> appSaveMusicMenu(MusicMenuDTO musicMenuDTO) {
        // 登录信息验证
        UserDTO userDTO = new UserDTO(musicMenuDTO.getToken());
        ResponseDTO<UserDTO> loginUserResponse = userService.getLoginUser(userDTO);
        if(!CodeMsg.SUCCESS.getCode().equals(loginUserResponse.getCode())) {
            return ResponseDTO.errorByMsg(CodeMsg.USER_SESSION_EXPIRED);
        }
        userDTO = loginUserResponse.getData();
        musicMenuDTO.setUserId(userDTO.getId());
        return saveMusicMenu(musicMenuDTO);
    }

    /**
     * 根据用户id获取歌单数据
     * @param musicMenuDTO
     * @return
     */
    @Override
    public ResponseDTO<List<MusicMenuDTO>> getMusicMenuListByUserId(MusicMenuDTO musicMenuDTO) {
        // 登录信息验证
        UserDTO userDTO = new UserDTO(musicMenuDTO.getToken());
        ResponseDTO<UserDTO> loginUserResponse = userService.getLoginUser(userDTO);
        if(!CodeMsg.SUCCESS.getCode().equals(loginUserResponse.getCode())) {
            return ResponseDTO.errorByMsg(CodeMsg.USER_SESSION_EXPIRED);
        }
        userDTO = loginUserResponse.getData();
        MusicMenuExample musicMenuExample = new MusicMenuExample();
        musicMenuExample.createCriteria().andUserIdEqualTo(userDTO.getId());
        musicMenuExample.setOrderByClause("create_time desc");
        List<MusicMenu> musicMenuList = musicMenuMapper.selectByExample(musicMenuExample);
        List<MusicMenuDTO> musicMenuDTOList = CopyUtil.copyList(musicMenuList, MusicMenuDTO.class);
        // 查询每个歌单下包含的音乐总数
        for(MusicMenuDTO item : musicMenuDTOList) {
            MusicMenuItemExample musicMenuItemExample = new MusicMenuItemExample();
            musicMenuItemExample.createCriteria().andMusicMenuIdEqualTo(item.getId());
            List<MusicMenuItem> musicMenuItemList = musicMenuItemMapper.selectByExample(musicMenuItemExample);
            item.setTotal(musicMenuItemList.size());
        }
        return ResponseDTO.success(musicMenuDTOList);
    }

    /**
     * 添加音乐到歌单
     * @param musicMenuItemDTO
     * @return
     */
    @Override
    public ResponseDTO<Boolean> addMusicMenu(MusicMenuItemDTO musicMenuItemDTO) {
        if(CommonUtil.isEmpty(musicMenuItemDTO.getMusicId()) || CommonUtil.isEmpty(musicMenuItemDTO.getMusicMenuId())) {
            return ResponseDTO.errorByMsg(CodeMsg.DATA_ERROR);
        }
        MusicMenuItem musicMenuItem = CopyUtil.copy(musicMenuItemDTO, MusicMenuItem.class);
        MusicMenuItemExample musicMenuItemExample = new MusicMenuItemExample();
        musicMenuItemExample.createCriteria()
                .andMusicIdEqualTo(musicMenuItem.getMusicId())
                .andMusicMenuIdEqualTo(musicMenuItem.getMusicMenuId());
        List<MusicMenuItem> musicMenuItemList = musicMenuItemMapper.selectByExample(musicMenuItemExample);
        if(musicMenuItemList.size() > 0) {
            return ResponseDTO.errorByMsg(CodeMsg.MUSIC_MENU_ITEM_EXIST);
        }
        musicMenuItem.setCreateTime(new Date());
        musicMenuItem.setId(UuidUtil.getShortUuid());
        if(musicMenuItemMapper.insertSelective(musicMenuItem) == 0) {
            return ResponseDTO.errorByMsg(CodeMsg.MUSIC_MENU_ITEM_ADD_ERROR);
        }
        return ResponseDTO.successByMsg(true, "添加成功！");
    }

    /**
     * 搜索歌单数据
     * @param musicMenuDTO
     * @return
     */
    @Override
    public ResponseDTO<List<MusicMenuDTO>> searchMusicMenu(MusicMenuDTO musicMenuDTO) {
        MusicMenuExample musicMenuExample = new MusicMenuExample();
        if(!CommonUtil.isEmpty(musicMenuDTO.getName())) {
            musicMenuExample.createCriteria().andNameLike("%" + musicMenuDTO.getName() + "%");
        }
        musicMenuExample.setOrderByClause("create_time desc");
        List<MusicMenu> musicMenuList = musicMenuMapper.selectByExample(musicMenuExample);
        return ResponseDTO.success(CopyUtil.copyList(musicMenuList, MusicMenuDTO.class));
    }

    /**
     * 歌单浏览量增加
     * @param musicMenuDTO
     * @return
     */
    @Override
    public ResponseDTO<Boolean> addMusicMenuView(MusicMenuDTO musicMenuDTO) {
        if(CommonUtil.isEmpty(musicMenuDTO.getId())) {
            return ResponseDTO.errorByMsg(CodeMsg.DATA_ERROR);
        }
        MusicMenu musicMenu = musicMenuMapper.selectByPrimaryKey(musicMenuDTO.getId());
        if(musicMenu == null) {
            return ResponseDTO.errorByMsg(CodeMsg.MUSIC_MENU_NOT_EXIST);
        }
        musicMenu.setViewNum(musicMenu.getViewNum() + 1);
        musicMenuMapper.updateByPrimaryKeySelective(musicMenu);
        return ResponseDTO.success(true);
    }

    /**
     * 根据是否官方歌单筛选数据
     * @param musicMenuDTO
     * @return
     */
    @Override
    public ResponseDTO<List<MusicMenuDTO>> getMusicMenuByIsOfficial(MusicMenuDTO musicMenuDTO) {
        MusicMenuExample musicMenuExample = new MusicMenuExample();
        if(musicMenuDTO.getIsOfficial() != null && musicMenuDTO.getIsOfficial() != 0) {
            musicMenuExample.createCriteria().andIsOfficialEqualTo(musicMenuDTO.getIsOfficial());
        }
        List<MusicMenu> musicMenuList = musicMenuMapper.selectByExample(musicMenuExample);
        List<MusicMenuDTO> musicMenuDTOList = CopyUtil.copyList(musicMenuList, MusicMenuDTO.class);
        return ResponseDTO.success(musicMenuDTOList);
    }

    /**
     * 根据id获取歌单数据
     * @param musicMenuDTO
     * @return
     */
    @Override
    public ResponseDTO<MusicMenuDTO> getMusicMenuById(MusicMenuDTO musicMenuDTO) {
        if(CommonUtil.isEmpty(musicMenuDTO.getId())) {
            return ResponseDTO.errorByMsg(CodeMsg.DATA_ERROR);
        }
        MusicMenu musicMenu = musicMenuMapper.selectByPrimaryKey(musicMenuDTO.getId());

        return ResponseDTO.success(CopyUtil.copy(musicMenu, MusicMenuDTO.class));
    }

    /**
     * 获取热门歌单数据
     * @param pageDTO
     * @return
     */
    @Override
    public ResponseDTO<List<MusicMenuDTO>> getHotMusicMenuList(PageDTO<MusicMenuDTO> pageDTO) {
        MusicMenuExample musicMenuExample = new MusicMenuExample();
        musicMenuExample.setOrderByClause("view_num desc");
        if(pageDTO.getSize() != null && pageDTO.getPage() != null) {
            PageHelper.startPage(pageDTO.getPage(), pageDTO.getSize());
        }
        List<MusicMenu> musicMenuList = musicMenuMapper.selectByExample(musicMenuExample);
        return ResponseDTO.success(CopyUtil.copyList(musicMenuList, MusicMenuDTO.class));
    }

    /**
     * 获取歌单总数
     * @return
     */
    @Override
    public ResponseDTO<Integer> getMusicMenuTotal() {
        return ResponseDTO.success(musicMenuMapper.countByExample(new MusicMenuExample()));
    }

    /**
     * 删除歌单详情数据
     * @param musicMenuItemDTO
     * @return
     */
    @Override
    public ResponseDTO<Boolean> removeMusicMenuItem(MusicMenuItemDTO musicMenuItemDTO) {
        if(CommonUtil.isEmpty(musicMenuItemDTO.getMusicMenuId()) || CommonUtil.isEmpty(musicMenuItemDTO.getMusicId())) {
            return ResponseDTO.errorByMsg(CodeMsg.DATA_ERROR);
        }
        MusicMenuItemExample musicMenuItemExample = new MusicMenuItemExample();
        musicMenuItemExample.createCriteria().andMusicIdEqualTo(musicMenuItemDTO.getMusicId()).andMusicMenuIdEqualTo(musicMenuItemDTO.getMusicMenuId());
        if(musicMenuItemMapper.deleteByExample(musicMenuItemExample) == 0) {
            return ResponseDTO.errorByMsg(CodeMsg.MUSIC_MENU_ITEM_DELETE_ERROR);
        }
        return ResponseDTO.successByMsg(true, "删除成功！");
    }

    /**
     * 判断歌单是否是当前登录用户的
     * @param musicMenuDTO
     * @return
     */
    @Override
    public ResponseDTO<Boolean> getIsMySelfMusicMenu(MusicMenuDTO musicMenuDTO) {
        if(CommonUtil.isEmpty(musicMenuDTO.getId())) {
            return ResponseDTO.errorByMsg(CodeMsg.DATA_ERROR);
        }
        // 登录信息验证
        UserDTO userDTO = new UserDTO(musicMenuDTO.getToken());
        ResponseDTO<UserDTO> loginUserResponse = userService.getLoginUser(userDTO);
        if(!CodeMsg.SUCCESS.getCode().equals(loginUserResponse.getCode())) {
            return ResponseDTO.errorByMsg(CodeMsg.USER_SESSION_EXPIRED);
        }
        userDTO = loginUserResponse.getData();
        MusicMenu musicMenuDB = musicMenuMapper.selectByPrimaryKey(musicMenuDTO.getId());
        if(musicMenuDB.getUserId().equals(userDTO.getId())) {
            return ResponseDTO.success(true);
        } else {
            return ResponseDTO.success(false);
        }
    }


    /**
     * 判断该用户的歌单是否存在
     * @param musicMenu
     * @param id
     * @return
     */
    public Boolean isMusicMenuExist(MusicMenu musicMenu, String id) {
        MusicMenuExample musicMenuExample = new MusicMenuExample();
        musicMenuExample.createCriteria().andNameEqualTo(musicMenu.getName()).andUserIdEqualTo(musicMenu.getUserId());
        List<MusicMenu> selectedMusicMenuList = musicMenuMapper.selectByExample(musicMenuExample);
        if(selectedMusicMenuList != null && selectedMusicMenuList.size() > 0) {
            if(selectedMusicMenuList.size() > 1){
                return true; //出现重名
            }
            if(!selectedMusicMenuList.get(0).getId().equals(id)) {
                return true; //出现重名
            }
        }
        return false;//没有重名
    }
}
